package com.cyz.aop;

import com.cyz.annotation.AuthCheck;
import com.cyz.exception.ErrorCode;
import com.cyz.exception.ThrowUtils;
import com.cyz.model.entity.User;
import com.cyz.model.enums.UserRoleEnums;
import com.cyz.service.UserService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@Aspect
@Component
public class AuthInterceptor {

    @Resource
    private UserService userService;

    /**
     * 执行拦截器
     *
     * @param joinPoint 切入点
     * @param authCheck 权限校验注解
     */
    @Around("@annotation(authCheck)")
    public Object doInterceptor(ProceedingJoinPoint joinPoint, AuthCheck authCheck) throws Throwable {
        // 通过注解获取方法所需的权限
        String mustRole = authCheck.mustRole();
        UserRoleEnums mustRoleEnums = UserRoleEnums.getEnumByValue(mustRole);
        // 1.获取request **
        RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
        HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
        // 2.获取登录用户信息
        User loginUser = userService.getLoginUser(request);
        UserRoleEnums userRoleEnums = UserRoleEnums.getEnumByValue(loginUser.getUserRole());
        // 3.判断用户权限
        // 3.1 方法不需要权限，直接放行
        if (mustRoleEnums == null) {
            return joinPoint.proceed();
        }
        // 3.2 方法需要权限，但是与用户的权限不匹配，抛出异常
        /*UserRoleEnums.ADMIN.equals(userRoleEnums) && !UserRoleEnums.ADMIN.equals(userRoleEnums)*/
        ThrowUtils.throwIf(!mustRoleEnums.equals(userRoleEnums), ErrorCode.NO_AUTH_ERROR);

        // 权限校验通过，放行
        return joinPoint.proceed();
    }
}
